package com.guonl.help;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SqlPlaceholderParser {

    // 方法：匹配IN子句中的占位符，并返回它们的索引
    public static List<Integer> getPlaceholderIndices(String sql, String fieldName) {
        // 构建针对IN子句的正则表达式
        String regex = "\\b" + fieldName + "\\s+IN\\s*\\(\\s*\\?\\s*(,\\s*\\?\\s*)*\\)";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(sql);

        List<Integer> indices = new ArrayList<>();
        int currentQuestionMarkIndex = 0; // 当前全局的问号索引

        // 统计全局问号的序列
        List<Integer> allQuestionMarkIndices = new ArrayList<>();
        for (int i = 0; i < sql.length(); i++) {
            if (sql.charAt(i) == '?') {
                allQuestionMarkIndices.add(currentQuestionMarkIndex++);
            }
        }

        // 当匹配字段时，找到该字段的IN子句中的占位符位置
        if (matcher.find()) {
            String matchedClause = matcher.group();
            System.out.println(matchedClause);
            int fromIndex = sql.indexOf(matchedClause);
            int endIndex = fromIndex + matchedClause.length();
            System.out.println("fromIndex：" + fromIndex);
            System.out.println("endIndex：" + endIndex);
            int numPlaceholders = countOccurrences(matchedClause, '?'); // 统计子句中的问号数量
            for (int i = 0; i < numPlaceholders; i++) {
                // 将全局问号序列中对应位置的索引加入结果
                indices.add(allQuestionMarkIndices.get(i));
            }
        }

        return indices;
    }

    // 帮助方法：统计字符串中某字符出现的次数
    private static int countOccurrences(String str, char ch) {
        int count = 0;
        for (char c : str.toCharArray()) {
            if (c == ch) {
                count++;
            }
        }
        return count;
    }

    public static void main(String[] args) {
        String sql = "SELECT user_id, user_name, phone FROM t_user WHERE user_name = ? AND phone IN (?, ?, ?)";

        // 测试phone字段的IN子句
        List<Integer> indices = getPlaceholderIndices(sql, "phone");
        System.out.println("phone IN clause indices: " + indices);

//        // 测试user_name字段
//        indices = getPlaceholderIndices(sql, "user_name");
//        System.out.println("user_name indices: " + indices);
    }


}


